package main

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Book struct {
	ID          bson.ObjectId `bson:"_id,omitempty" json:"id"`
	Type        string        `bson:"type" json:"type"`
	BookName    string        `bson:"bookName" json:"bookName" binding:"required"`
	Description string        `bson:"description" json:"description"`
	Prompt      string        `bson:"prompt" json:"prompt"`
	Settings    string        `bson:"settings" json:"settings"`
	CreateTime  time.Time     `bson:"createTime" json:"createTime"`
	UpdateTime  time.Time     `bson:"updateTime" json:"updateTime"`
	// TemplatesId bson.ObjectId `bson:"templatesId" json:"templatesId"`
}

func collection() *mgo.Collection {
	return GetSession().DB("mybook").C("books")
}

// 创建书籍
func CreateBook(book *Book) error {
	// if book.ID != "" {
	// 	return UpdateBook(book.ID.Hex(), bson.M{"bookName": book.BookName, "description": book.Description})
	// }
	book.CreateTime = time.Now()
	book.UpdateTime = time.Now()
	return collection().Insert(book)
}

// 获取书籍
func GetBook(id string) (*Book, error) {
	if !bson.IsObjectIdHex(id) {
		return nil, mgo.ErrNotFound
	}
	var book Book
	err := collection().FindId(bson.ObjectIdHex(id)).One(&book)
	return &book, err
}

// 更新书籍
func UpdateBook(id string, updateData bson.M) error {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}

	updateData["updateTime"] = time.Now()
	return collection().UpdateId(bson.ObjectIdHex(id), bson.M{"$set": updateData})
}

// 删除书籍
func DeleteBook(id string) (err error) {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}
	err = collection().RemoveId(bson.ObjectIdHex(id))
	err = DeleteChaptersByBook(id)
	err = DeleteElesByBook(id)
	return err
}

// 获取用户的所有书籍
func GetAllBook() ([]Book, error) {
	var books []Book
	err := collection().Find(nil).All(&books)
	return books, err
}
